package la.iok.hzsvn.lewin.movie.controller;

import la.iok.hzsvn.lewin.movie.core.RoleEnum;
import la.iok.hzsvn.lewin.movie.core.Token;
import la.iok.hzsvn.lewin.movie.core.exception.ErrorCode;
import la.iok.hzsvn.share.dfs.exception.DfsException;
import la.iok.hzsvn.share.dfs.model.DfsResult;
import la.iok.hzsvn.share.dfs.service.DfsService;
import la.iok.hzsvn.share.response.OperatorResponse;
import la.iok.hzsvn.share.utils.PathUtils;
import la.iok.hzsvn.share.utils.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
public class DfsFileController {
    private final DfsService dfsService;
    public DfsFileController(DfsService dfsService) {
        this.dfsService = dfsService;
    }

    /**
     * 测试使用,直接上传文件并保存
     * @return 操作结果
     */
    @PostMapping("dfs")
    public OperatorResponse upload(@RequestHeader Token token, MultipartFile file) throws IOException {
        ErrorCode.ADMIN_DENIED.assertTrue(token.hasAuthority(RoleEnum.Admin));
        String ofn = file.getOriginalFilename();
        if(StringUtils.isBlank(ofn)){
            throw new DfsException("文件名称不能为空");
        }
        File localTempFile = new File(PathUtils.getPath(), ofn);
        try{
            file.transferTo(localTempFile);
            DfsResult result = dfsService.uploadFile(localTempFile);
            return new OperatorResponse(result.success(),result.getMessage());
        } finally {
            localTempFile.delete();
        }
    }
}
